package com.wei.spring.web.user.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wei.spring.web.user.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 类的详细说明
 * 如果继承某个接口{@link StateContext}，提供一个链接，方便使用
 * <p>
 * 如果是过期的接口，那么请尽量提供用于替换的类的链接地址{@link StateContext}
 *
 * @param <S> 如果用到泛型，可以这样注释
 * @param <E> 如果用到泛型，可以这样注释
 * @author buhuan.wang
 * @since 2020/12/29
 */

public class LogInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long startTime = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        //请求路径
        json.put(CommonConstants.REQ_PATH, request.getRequestURI());
        //请求参数
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((key, value) -> {
            json.put(key, request.getParameter(key));
        });
        //记录请求开始时间
        request.setAttribute(CommonConstants.START_TIME, startTime);
        //traceId
        json.put(CommonConstants.TRACE_ID, MDC.get(CommonConstants.TRACE_ID));

        json.put(CommonConstants.LOG_TYPE, CommonConstants.START);

        logger.info(CommonConstants.LOG_PREFIX + json.toJSONString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex)
            throws Exception {
        JSONObject json = new JSONObject();
        Long startTime = (Long) request.getAttribute(CommonConstants.START_TIME);
        //请求耗时
        json.put(CommonConstants.CONSUME_TIME, System.currentTimeMillis() - startTime);
        //traceId
        json.put(CommonConstants.TRACE_ID, MDC.get(CommonConstants.TRACE_ID));
        //响应Data
        json.put(CommonConstants.RES_BODY, request.getAttribute(CommonConstants.RES_BODY));
        //日志类型
        json.put(CommonConstants.LOG_TYPE, CommonConstants.END);

        logger.info(CommonConstants.LOG_PREFIX + json.toJSONString());
    }

}
